/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.client;

import java.util.Date;

import net.bioteam.appweb.gwt.apps.client.Util.Util;
import net.bioteam.appweb.gwt.apps.client.login.LoginPanel;
import net.bioteam.appweb.gwt.apps.clientandserver.Constant;
import net.bioteam.appweb.gwt.apps.clientandserver.LoginProxy;
import net.bioteam.appweb.gwt.apps.clientandserver.LoginProxyAsync;

import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class LoginHolder
{

	public LoginPanel loginPanel;

	public LoginHolder()
	{
		loginPanel = new LoginPanel();
	}

	public void toRegister()
	{
		loginPanel.toRegister();
	}

	public void toRetrieve()
	{
		loginPanel.toRetrieve();
	}

	public void toLogin()
	{
		loginPanel.toLogin();
	}

	public static String getUsername()
	{
		if (Cookies.getCookie("_username") != null)
		{
			return Cookies.getCookie("_username");
		} else if (StaticHolder.user != null)
		{
			return StaticHolder.user.getName();
		} else
		{
			return "";
		}
	}

	public void logout()
	{
		LoginProxyAsync login = LoginProxy.Util.getInstance();
		login.logout(new AsyncCallback()
		{

			public void onFailure(Throwable caught)
			{

			}

			public void onSuccess(Object result)
			{

			}
		});
		String path = "/" + Constant.APPWEB_CONTEXT;
		Cookies.setCookie("JSESSIONID", "", new Date(0), null, path, false);
		Cookies.removeCookie("_username");
		Util.redirect("/" + Constant.APPWEB_CONTEXT + "/logout.html");
	}

	public void removeSession()
	{
		String path = "/" + Constant.APPWEB_CONTEXT;
		Cookies.setCookie("JSESSIONID", "", new Date(0), null, path, false);
	}

	public static boolean isLogined()
	{
		// JSESSION cookie is a session cookie which can only be removed after
		// the browser is closed.
		// however, we could set it to an empty value after logout is clicked.
		// So we need to test the empty value, not just null
		String sessionvalue = Cookies.getCookie("JSESSIONID");

		return sessionvalue != null && sessionvalue.length() > 0 ? true : false;
	}
	
	public static String hashPassword(String username, String password)
	{
		return Util.mymd5(password+"_"+username);
	}

}
